//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package user_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ResumeAccessDbItem struct {
	UserId             string `bson:"_id"`
	AllowProjectAccess bool   `bson:"allowProjectAccess"`
	AllowOrgAccess     bool   `bson:"allowOrgAccess"`
}

type _ResumeAccessDao struct {
	mc *mongo.Collection
}

func newResumeAccessDao(db *mongo.Database) (*_ResumeAccessDao, error) {
	mc := db.Collection(db_ns.DB_NS_USER + "resume_access")
	return &_ResumeAccessDao{mc: mc}, nil
}

func (db *_ResumeAccessDao) Set(ctx context.Context, dbItem *ResumeAccessDbItem) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": dbItem.UserId}, bson.M{"$set": dbItem}, options.Update().SetUpsert(true))
	return err
}

func (db *_ResumeAccessDao) Get(ctx context.Context, userId string) (*ResumeAccessDbItem, error) {
	retItem := &ResumeAccessDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": userId}).Decode(retItem)
	return retItem, err
}

func (db *_ResumeAccessDao) ListById(ctx context.Context, userIdList []string) ([]*ResumeAccessDbItem, error) {
	if len(userIdList) == 0 {
		return []*ResumeAccessDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": userIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*ResumeAccessDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
